package com.kinon.market.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.market.Constatus;
import com.kinon.market.R;
import com.kinon.market.adapter.UrgentBuyAdapter;
import com.kinon.market.entity.ShangpinEntity;
import com.kinon.market.sqlbean.BuyGoodsBean;
import com.kinon.market.sqlbean.GoodsBean;
import com.kinon.market.tools.HttpTools;
import com.kinon.market.tools.MyShowDialog;
import com.kinon.market.tools.NetWorkUtil;
import com.kinon.market.view.JiesuanjineActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.math.BigDecimal;
import java.util.ArrayList;

/**
 * 收银
 */

public class ShouyinFragment extends Fragment implements OnClickListener,
        UrgentBuyAdapter.OnAdapterClickListener {
    String token;
    //	private TextView tv_amount;
    String str = "";
    String tiaoma = "";
    int amount = 0;
    double total = 0.0;
    BigDecimal bg = new BigDecimal(total);
    double result = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    ShangpinAdapter shangpinAdapter;
    HttpTools toolModel = null;
    /**
     * 数字按钮
     */
    private Button btn_9;
    private Button btn_8;
    private Button btn_7;
    private Button btn_6;
    private Button btn_5;
    private Button btn_4;
    private Button btn_3;
    private Button btn_2;
    private Button btn_1;
    private Button btn_0;
    private Button btn_shanchu;
    private Button btn_queren;
    /**
     * 收款
     */
    private Button btn_shoukuan;
    /**
     * 清空
     */
    private Button btn_qingkong;
    /**
     * 编码输入框
     */
    private EditText et_jiesuan;
    /**
     * 扫码输入框
     */
    private EditText et_id;
    /**
     * 商品总数
     */
    private TextView tv_amount;
    private ListView lv;
    /**
     * 商品信息的集合
     */
    private ArrayList<ShangpinEntity> shangpinlist;
    private ArrayList<BuyGoodsBean> buyList;
    private UrgentBuyAdapter buyAdapter;
    /**
     * EditText监听
     */
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public synchronized void afterTextChanged(Editable s) {
//	    	Toast.makeText(getActivity(), "4", 1).show();
            if (et_id.getText().length() == 13) {
                String str = et_id.getText().toString();
                if (!Constatus.URGENT_TYPE) {
                    getShangpininfo1(str);
                } else {
                    urgent(str);
                }
            }


        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shouyin, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initRes();
    }

    @Override
    public void onStart() {
        super.onStart();
        et_id.requestFocus();
    }

    private void initRes() {
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");

        lv = (ListView) getView().findViewById(R.id.lv);
        et_id = (EditText) getView().findViewById(R.id.et_id);
        btn_9 = (Button) getView().findViewById(R.id.btn_9);
        btn_8 = (Button) getView().findViewById(R.id.btn_8);
        btn_7 = (Button) getView().findViewById(R.id.btn_7);
        btn_6 = (Button) getView().findViewById(R.id.btn_6);
        btn_5 = (Button) getView().findViewById(R.id.btn_5);
        btn_4 = (Button) getView().findViewById(R.id.btn_4);
        btn_3 = (Button) getView().findViewById(R.id.btn_3);
        btn_2 = (Button) getView().findViewById(R.id.btn_2);
        btn_1 = (Button) getView().findViewById(R.id.btn_1);
        btn_0 = (Button) getView().findViewById(R.id.btn_0);
        btn_shanchu = (Button) getView().findViewById(R.id.btn_shanchu);
        btn_queren = (Button) getView().findViewById(R.id.btn_queren);
        btn_shoukuan = (Button) getView().findViewById(R.id.btn_shoukuan);
        btn_qingkong = (Button) getView().findViewById(R.id.btn_qingkong);
        tv_amount = (TextView) getView().findViewById(R.id.tv_amount);
        et_jiesuan = (EditText) getView().findViewById(R.id.et_shuru);

        et_jiesuan.setFocusable(false);
        tv_amount.setText("共计" + amount + "件商品");
        btn_shoukuan.setText("收款");

        if (!Constatus.URGENT_TYPE) {
            shangpinlist = new ArrayList<ShangpinEntity>();
            shangpinAdapter = new ShangpinAdapter(getActivity(), shangpinlist);
            lv.setAdapter(shangpinAdapter);
            lv.setDivider(null);
        } else {
            buyList = new ArrayList<>();
            buyAdapter = new UrgentBuyAdapter(getActivity(), buyList);
            lv.setAdapter(buyAdapter);
            buyAdapter.setAdapterClickListener(this);
        }

        et_id.addTextChangedListener(watcher);
        addOnClicik();
    }

    private void addOnClicik() {
        btn_9.setOnClickListener(this);
        btn_8.setOnClickListener(this);
        btn_7.setOnClickListener(this);
        btn_6.setOnClickListener(this);
        btn_5.setOnClickListener(this);
        btn_4.setOnClickListener(this);
        btn_3.setOnClickListener(this);
        btn_2.setOnClickListener(this);
        btn_1.setOnClickListener(this);
        btn_0.setOnClickListener(this);
        btn_shanchu.setOnClickListener(this);
        btn_queren.setOnClickListener(this);
        btn_shoukuan.setOnClickListener(this);
        btn_qingkong.setOnClickListener(this);

        btn_shanchu.setFocusable(false);
        btn_queren.setFocusable(false);
        btn_shoukuan.setFocusable(false);
        btn_qingkong.setFocusable(false);
        btn_shanchu.setFocusable(false);
        btn_9.setFocusable(false);
        btn_8.setFocusable(false);
        btn_7.setFocusable(false);
        btn_6.setFocusable(false);
        btn_5.setFocusable(false);
        btn_4.setFocusable(false);
        btn_3.setFocusable(false);
        btn_2.setFocusable(false);
        btn_1.setFocusable(false);
        btn_0.setFocusable(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_9:
                str = str + "9";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_8:
                str = str + "8";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_7:
                str = str + "7";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_6:
                str = str + "6";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_5:
                str = str + "5";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_4:
                str = str + "4";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_3:
                str = str + "3";
                et_jiesuan.setText(str);

                break;
            case R.id.btn_2:
                str = str + "2";
                et_jiesuan.setText(str);

                btn_2.setTextColor(getActivity().getResources().getColor(R.color.goodsPrice));
                break;
            case R.id.btn_1:
                str = str + "1";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_0:
                str = str + "0";
                et_jiesuan.setText(str);
                break;

            case R.id.btn_shanchu:
                if (str.length() == 0) {
                    return;
                } else {
                    str = str.substring(0, str.length() - 1);
                    et_jiesuan.setText(str);
                }
                break;
            case R.id.btn_queren:
                if (!Constatus.URGENT_TYPE) {
                    getShangpininfo2();
                } else {
                    urgent(str);
                }
                break;
            case R.id.btn_shoukuan:
                if (!Constatus.URGENT_TYPE) {
                    save();
                } else {
                    uReceipt();
                }
                break;
            case R.id.btn_qingkong:
                if (!Constatus.URGENT_TYPE) {
                    clearData();
                } else {
                    clearUrgentDate();
                }
                break;
            default:
                break;
        }
    }

    private void uReceipt() {
        if (buyList.size() == 0) {
            Toast.makeText(getActivity(), "请选择商品",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(getActivity(), JiesuanjineActivity.class);
        BigDecimal bg1 = new BigDecimal(result);
        double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        intent.putExtra("total", "" + f2);
        intent.putExtra("totalamount", amount + "");
        intent.putExtra("buyList", buyList);
        startActivity(intent);
//		clearData();
        clearUrgentDate();
    }

    @Override
    public void onItemClick(int position, int button) {
        // button是减
        if (button == 0) {
            amount -= 1;
            result = result - buyList.get(position).getPrice();
            int num = buyList.get(position).getAmount() - 1;
            buyList.get(position).setAmount(num);
            if (num == 0) {
                buyList.remove(position);
            }
        } else {
            amount += 1;
            result = result + buyList.get(position).getPrice();
            int num = buyList.get(position).getAmount() + 1;
            buyList.get(position).setAmount(num);
        }
        BigDecimal bg1 = new BigDecimal(result);
        double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        btn_shoukuan.setText("收款" + "￥" + f2);
        tv_amount.setText("共计" + amount + "件商品");
        buyAdapter.notifyDataSetChanged();

    }

    /**
     * 清空数据
     */
    private void clearData() {
        shangpinlist.removeAll(shangpinlist);
        shangpinAdapter.notifyDataSetChanged();
        total = 0.0;
        result = 0.0;
        amount = 0;
        tv_amount.setText("共计" + amount + "件商品");
        btn_shoukuan.setText("收款");
    }

    private void clearUrgentDate() {
        buyList.clear();
        buyAdapter.notifyDataSetChanged();
        total = 0.0;
        result = 0.0;
        amount = 0;
        str = "";
        tv_amount.setText("共计" + amount + "件商品");
        btn_shoukuan.setText("收款");
    }

    /**
     * 扫码获取商品信息
     */
    private void getShangpininfo1(String tiaoma) {
        if (NetWorkUtil.isNetwork(getActivity()) == false) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        toolModel = new HttpTools(getActivity());
        toolModel.bycode(token, tiaoma,
                new JsonShangpin());
    }

    /**
     * 输入编号获取商品信息
     */
    private void getShangpininfo2() {
        if (NetWorkUtil.isNetwork(getActivity()) == false) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            btn_queren.setEnabled(true);
            return;
        }
        btn_queren.setEnabled(false);
        toolModel = new HttpTools(getActivity());
        toolModel.bycode(token, str,
                new JsonShangpin());
    }

    /**
     * 提交商品信息
     */
    private void save() {
        btn_shoukuan.setEnabled(false);
        toolModel = new HttpTools(getActivity());
        if (NetWorkUtil.isNetwork(getActivity()) == false) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            btn_shoukuan.setEnabled(true);
            return;
        }
        if (shangpinlist.size() == 0) {
            Toast.makeText(getActivity(), "请添加商品！", Toast.LENGTH_SHORT).show();
            btn_shoukuan.setEnabled(true);
            return;
        } else {
            Gson gson = new Gson(); // 实例化Gson对象
            String data = gson.toJson(shangpinlist);
//			Log.e("zq", "JsonObject-------"+data);
            toolModel.shouyinsave(token, data, "", result + "",
                    new JsonSave());
        }
    }

    private void urgent(String card) {
        synchronized (card) {
            et_id.setText("");

//			ArrayList<GoodsBean> list= (ArrayList<GoodsBean>) DataSupport.findAll(GoodsBean.class);
//			Gson gson=new Gson();
//			String data=gson.toJson(list);
//			Log.e("lh", "data== "+data);

            ArrayList<GoodsBean> goods = (ArrayList<GoodsBean>)
                    DataSupport.where("code=?", card).find(GoodsBean.class);
            if (goods == null || goods.size() == 0) {
                Toast.makeText(getActivity(), "本地未查询到此商品",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            //是否有相同的商品
            boolean isSameGoods = false;
            if (buyList.size() != 0) {
                for (int i = 0; i < buyList.size(); i++) {
                    if (goods.get(0).getGid().equals(buyList.get(i).getGoodsid())) {
                        buyList.get(i).setAmount(buyList.get(i).getAmount() + 1);
                        isSameGoods = true;
                    }
                }
                if (!isSameGoods) {
                    buyList.add(new BuyGoodsBean(goods.get(0).getGid(), goods.get(0).getCode(),
                            goods.get(0).getName(), goods.get(0).getPurchaseprice(), 1));
                }
            } else {
                buyList.add(new BuyGoodsBean(goods.get(0).getGid(), goods.get(0).getCode(),
                        goods.get(0).getName(), goods.get(0).getPurchaseprice(), 1));
            }
            et_jiesuan.setText("");
            buyAdapter.notifyDataSetChanged();
            amount += 1;
            str = "";
            result = result + goods.get(0).getPurchaseprice();
            BigDecimal bg1 = new BigDecimal(result);
            double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            btn_shoukuan.setText("收款" + "￥" + f2);
            tv_amount.setText("共计" + amount + "件商品");


        }
    }

    private class JsonShangpin extends JsonHttpResponseHandler {
        boolean flag = false;
        int index;

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    JSONObject data = response.getJSONObject("data");
                    String id = data.getString("id");
//						String gcategory_id=data.getString("gcategory_id");
                    String code1 = data.getString("code");
                    String name = data.getString("name");
                    String purchaseprice = data.getString("purchaseprice");
                    for (int i = 0; i < shangpinlist.size(); i++) {
                        if (shangpinlist.get(i).getCode().equals(code1)) {
                            index = i;
                            flag = true;
                            continue;
                        }/*else {
                            flag=false;
						}*/
                    }
                    if (flag == true) {
                        shangpinlist.get(index).setAmount("" + (Integer.parseInt(shangpinlist.get(index).getAmount()) + 1));
                        double num1 = Double.parseDouble(shangpinlist.get(index).getTotalprice());
                        double num2 = Double.parseDouble(shangpinlist.get(index).getPrice());
                        double xiaoji = num1 + num2;
                        BigDecimal bg = new BigDecimal(xiaoji);
                        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        shangpinlist.get(index).setTotalprice("" + f1);
                    } else {
                        shangpinlist.add(0, new ShangpinEntity(id, code1, name, purchaseprice, "1", purchaseprice));
                    }
                    shangpinAdapter.notifyDataSetChanged();
                    btn_queren.setEnabled(true);
                    str = "";
                    et_jiesuan.setText(str);
                    et_id.setText("");
                    amount = amount + 1;
                    double xiaoji = Double.parseDouble(purchaseprice);
                    result = result + xiaoji;
                    BigDecimal bg1 = new BigDecimal(result);
                    double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    btn_shoukuan.setText("收款" + "￥" + f2);
                    tv_amount.setText("共计" + amount + "件商品");
                } else {
                    et_id.setText("");
                    btn_queren.setEnabled(true);
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Toast.makeText(getActivity(), "网络请求超时",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private class JsonSave extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(getActivity(), "订单生成中....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            try {
//				Log.i("info","提交订单----"+response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    String data = response.getString("data");
                    btn_shoukuan.setEnabled(true);
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), JiesuanjineActivity.class);
                    BigDecimal bg1 = new BigDecimal(result);
                    double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    intent.putExtra("total", "" + f2);
                    intent.putExtra("orderid", data);
                    startActivity(intent);

                    clearData();
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                } else {
                    btn_shoukuan.setEnabled(true);
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            MyShowDialog.closeLoadingDialog();
            Toast.makeText(getActivity(), "网络请求超时",
                    Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 商品适配器
     */
    public class ShangpinAdapter extends BaseAdapter {
        Context context;
        ArrayList<ShangpinEntity> shangpinList;
        HttpTools httpTools = null;

        public ShangpinAdapter(Context context, ArrayList<ShangpinEntity> shangpinList) {
            super();
            this.context = context;
            this.shangpinList = shangpinList;
        }

        @Override
        public int getCount() {
            return shangpinList.size();
        }

        @Override
        public Object getItem(int position) {
            return shangpinList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View view, ViewGroup parent) {
            final ViewHandle handle;
            if (view == null) {
                handle = new ViewHandle();
                view = LayoutInflater.from(context).inflate(R.layout.item_shangpin, null);
                handle.tv_tiaoma = (TextView) view.findViewById(R.id.tv_tiaoma);
                handle.tv_name = (TextView) view.findViewById(R.id.tv_name);
                handle.tv_jiage = (TextView) view.findViewById(R.id.tv_jiage);
                handle.ib_jia = (ImageButton) view.findViewById(R.id.ib_jia);
                handle.ib_jian = (ImageButton) view.findViewById(R.id.ib_jian);
                handle.et_amount = (EditText) view.findViewById(R.id.et_amount);
                handle.tv_xiaoji = (TextView) view.findViewById(R.id.tv_xiaoji);
//				handle.tv_sname=(TextView)view.findViewById(R.id.tv_sname);
                view.setTag(handle);
            } else {
                handle = (ViewHandle) view.getTag();
            }
            handle.tv_tiaoma.setText(shangpinList.get(position).getCode());
            handle.tv_name.setText(shangpinList.get(position).getName());
            handle.et_amount.setText(shangpinList.get(position).getAmount());
            handle.tv_jiage.setText("￥" + shangpinList.get(position).getPrice());
            handle.tv_xiaoji.setText("￥" + shangpinList.get(position).getTotalprice());
            handle.ib_jia.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    int goodsNum = Integer.parseInt(handle.et_amount.getText().toString());
                    goodsNum++;
                    handle.et_amount.setText("" + goodsNum);
                    shangpinList.get(position).setAmount("" + goodsNum);
                    double price = Double.parseDouble(shangpinList.get(position).getPrice());
                    double amount1 = Double.parseDouble(handle.et_amount.getText().toString());
                    double xiaoji = price * amount1;
                    BigDecimal bg = new BigDecimal(xiaoji);
                    double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    handle.tv_xiaoji.setText("￥" + f1);
                    shangpinList.get(position).setTotalprice("" + f1);
                    amount = amount + 1;
                    result = result + price;
                    BigDecimal bg1 = new BigDecimal(result);
                    double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    btn_shoukuan.setText("收款" + "￥" + f2);
                    tv_amount.setText("共计" + amount + "件商品");
                }
            });
            handle.ib_jian.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    int goodsNum = Integer.parseInt(handle.et_amount.getText().toString());
                    goodsNum--;
                    if (goodsNum <= 0) {
                        amount = amount - 1;
                        double price = Double.parseDouble(shangpinList.get(position).getPrice());
                        result = result - price;
//						shangpinList.get(position).setTotalprice(""+Double.parseDouble(shangpinList.get(position).getPrice())*Integer.parseInt(handle.et_amount.getText().toString()));
                        BigDecimal bg1 = new BigDecimal(result);
                        double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        btn_shoukuan.setText("收款" + "￥" + f2);
                        tv_amount.setText("共计" + amount + "件商品");
                        shangpinlist.remove(position);
                        shangpinAdapter.notifyDataSetChanged();
                        return;
                    }
                    handle.et_amount.setText("" + goodsNum);
                    shangpinList.get(position).setAmount("" + goodsNum);
                    double price = Double.parseDouble(shangpinList.get(position).getPrice());
                    double amount1 = Double.parseDouble(handle.et_amount.getText().toString());
                    double xiaoji = price * amount1;
                    BigDecimal bg = new BigDecimal(xiaoji);
                    double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    handle.tv_xiaoji.setText("￥" + f1);
                    shangpinList.get(position).setTotalprice("" + f1);
                    amount = amount - 1;
                    double price1 = Double.parseDouble(shangpinList.get(position).getPrice());
                    result = result - price1;
                    BigDecimal bg1 = new BigDecimal(result);
                    double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    btn_shoukuan.setText("收款" + "￥" + f2);
                    tv_amount.setText("共计" + amount + "件商品");
                }
            });

            return view;
        }

        class ViewHandle {
            /**
             * 条码
             */
            TextView tv_tiaoma;
            /**
             * 商品名
             */
            TextView tv_name;
            /**
             * 加
             */
            ImageButton ib_jia;
            /**
             * 数量
             */
            EditText et_amount;
            /**
             * 减
             */
            ImageButton ib_jian;
            /**
             * 价格
             */
            TextView tv_jiage;
            /**
             * 小计
             */
            TextView tv_xiaoji;
        }
    }

}
